package com.feituan.core.token;



import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.feituan.core.persistence.service.SysUserService;
import com.feituan.core.pojo.entity.SysUser;
import com.feituan.core.redis.cache.RedisCache;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.KeyLengthException;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.Key;
import java.text.ParseException;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class TokenServer {

    @Resource
    private RedisCache redisCache;

    @Resource
    private SysUserService sysUserService;
    /**
     * 创建秘钥
     */
    private static final byte[] SECRET = "qngChengBoYa-realtimeWuIngWangJiaQiZhangYv".getBytes();

    private static final String KEY = "token:";

    /**
     * 生成token
     * @param username
     * @return {@link String}
     */
    public String buildToken(String username) {

        try {

            // 创建一个32-byte的密匙
            MACSigner macSigner = new MACSigner(SECRET);
            // 建立payload 载体
            JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
                    .subject("login")
                    .claim("USERNAME",username)
                    .issueTime(new Date())
                    .build();

            //建立签名
            SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);
            signedJWT.sign(macSigner);

            // 生成token
            String token = signedJWT.serialize();
            // 查询用户
            SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(true, SysUser::getUsername, username));
            sysUser.setPassword(null);
            redisCache.setCacheObject(KEY + token,sysUser,120, TimeUnit.MINUTES);
            return token;
        } catch (KeyLengthException e) {
            e.printStackTrace();
        } catch (JOSEException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public boolean verifyToken(String token) {

        // 判断redis中是否存在token信息，有则给该token续期
        if (redisCache.hasKey(KEY + token)) {
            redisCache.expire(KEY + token,10,TimeUnit.MINUTES);
            return true;
        }
        return false;
    }

}
